blog

Home / DeveloperSection / Blogs / Exception Handling in C++

Exception Handling in C++

priyanka kushwaha2126 05-Feb-2015

In this blog, I’m explaining about Exception handling in C++

 

An  exception  is a problem that arises during the execution of a program Exceptions provide a way to transfer control from one part of a program to another.

C++ exception handling is built upon three  keywords: _try, catch and throw.

throw: A program throws an exception when a program show up. This is done using a throw keyword.

try: A try block identifies a block of a code for which particular exceptions will be activated. It’s followed by one or more catch blocks.

catch: A program catches an exception  with  an exception handler at the place in a program where you want to handle the problem. This is done using a catch keyword.

Example:
// Exception.cpp : main project file.
 
#include"stdafx.h"
#include<iostream>
#include<exception>
#include<Windows.h>
usingnamespace std;
usingnamespace System;
 
int main(array<System::String ^> ^args)
{
    _try
            {
                        int firstNum,secNum,res;
                        cout<<"Enter first number";
                        cin>>firstNum;
                        cout<<"Enter second number";
                        cin>>secNum;
             if(secNum==0)
                throw;
                        res=firstNum/secNum;
                        cout<<"Result="<<res;
            }
            _except(EXCEPTION_FLT_DIVIDE_BY_ZERO)
            {
                        cout<<"InValid data";
            }
            Console::ReadKey(0);
    return 0;
}

Updated 05-Feb-2015

Leave Comment

Comments

Liked By